package com.mybatis.utils;

import org.apache.ibatis.io.Resources;
import org.apache.ibatis.session.SqlSession;
import org.apache.ibatis.session.SqlSessionFactory;
import org.apache.ibatis.session.SqlSessionFactoryBuilder;

import java.io.Reader;
//MyBatisUtils 作用：创建全局唯一的 SqlSessionFactory对象
public class MyBatisUtils {
    //利用了static(静态)属于类不属于对象，且全局唯一
    private static SqlSessionFactory sqlSessionFactory = null;
    static {
        Reader reader = null;
        try {
            reader = Resources.getResourceAsReader("mybatis-config.xml");
            sqlSessionFactory = new SqlSessionFactoryBuilder().build(reader);
        }catch (Exception e) {
            e.printStackTrace();
            throw new ExceptionInInitializerError(e);//初始化类的过程中的异常抛出去
        }
    }
    public static  SqlSession openSession() { //开session
        return sqlSessionFactory.openSession();
    }
    public static void closeSession(SqlSession session) { //关session
        if (session != null) {
            session.close();
        }
    }
}
